import { HttpErrorResponse, HttpEvent, HttpHandler, HttpHeaderResponse, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, Observable, throwError } from 'rxjs';
import { AppService } from './app.service';

@Injectable({
  providedIn: 'root'
})
export class ErrorInterceptorService implements HttpInterceptor {

  constructor(private _appService: AppService, private _router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError(error => {
        console.log(`请求 with status ${error.status}, statusText ${error.statusText}, 
        httpCode ${error.HttpStatusCode}, error ${error.error}, progressType ${error.type}`);
        const text = '请求失败';

        switch (error.status) {
          case 400:
          case 401:
          case 403:
          case 404:
            console.log('resp with 40x');
            this._appService.removeToken();
            this._router.navigateByUrl("/");
            break;
        }
        return throwError(() => text);
      })
    );
  }
}
